<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace ckeeper\utils;


use Selibra\Http\Lib\Request;

class Ip
{

    /**
     * 获取客户端IP地址
     * @param Request $request
     * @param int $type
     * @return mixed
     */
    public static function getRequestIp(Request $request, $type = 0)
    {
        $type = $type ? 1 : 0;
        $server = $request->server();
        $ip = null;
        if (isset($server['http_x_forwarded_for'])) {
            $arr = explode(',', $server['http_x_forwarded_for']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }
            $ip = trim($arr[0]);
        } elseif (isset($server['http_client_ip'])) {
            $ip = $server['http_client_ip'];
        } elseif (isset($server['remote_addr'])) {
            $ip = $server['remote_addr'];
        }
        // IP地址合法验证
        $long = ip2long($ip);
        $ip = $long ? array($ip, $long) : array('127.0.0.1', 0);
        return $ip[$type];
    }

}
